import Treetable from './treetable.esm'
import {closest} from '../common/helper/dom'

/**
 * tree table ops
 * @param el
 * @param expanded
 * @returns {Treetable}
 */
export function treeify(el, expanded) {
  return new Treetable(el, {
    clickableNodeNames: true,
    expandable: true,
    indent: 35,
    onInitialized() {
      Object.keys(expanded).forEach(n => {
        this.expandNode(n)
      })
    },
    onNodeCollapse() {
      delete expanded[this.id]
    },
    onNodeExpand() {
      expanded[this.id] = 1
    }
  })
}

/**
 * 展开/收缩子元素
 * @param e
 * @param node
 * @param expanded
 */
export const toggleNode = function (e, node, expanded) {
  var parent = closest(e.target, 'li')
  if (!parent.classList.contains('parent')) return
  if (parent.classList.contains('open')) {
    parent.classList.remove('open')
    delete expanded[node.id]
  } else {
    parent.classList.add('open')
    expanded[node.id] = 1
  }
}